<template>
  <view class="ip-sharing-container">
    <!-- 顶部导航 -->
    <view class="nav-bar">
      <view class="nav-back" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <text class="nav-title">IP共享</text>
      <view class="nav-actions">
        <text class="nav-icon" @click="showUploadModal">+</text>
      </view>
    </view>

    <!-- 搜索和筛选 -->
    <view class="search-section">
      <view class="search-container">
        <input 
          v-model="searchKeyword" 
          class="search-input" 
          placeholder="搜索IP作品..."
          placeholder-class="placeholder"
          @input="onSearch"
        />
        <text class="search-icon">🔍</text>
      </view>
      
      <view class="filter-options">
        <view 
          v-for="filter in filters" 
          :key="filter.value"
          class="filter-option"
          :class="{ active: selectedFilter === filter.value }"
          @click="selectFilter(filter.value)"
        >
          <text class="filter-name">{{ filter.name }}</text>
        </view>
      </view>
    </view>

    <scroll-view class="content-scroll" scroll-y="true">
      <!-- IP列表 -->
      <view class="ip-list">
        <view 
          v-for="ip in filteredIPs" 
          :key="ip.id"
          class="ip-card"
          @click="viewIPDetail(ip)"
        >
          <view class="ip-header">
            <image class="ip-cover" :src="ip.cover" mode="aspectFill"></image>
            <view class="ip-badge" :class="ip.license">
              <text class="badge-text">{{ getLicenseText(ip.license) }}</text>
            </view>
          </view>
          
          <view class="ip-content">
            <text class="ip-name">{{ ip.name }}</text>
            <text class="ip-author">by {{ ip.author }}</text>
            <text class="ip-desc">{{ ip.description }}</text>
            
            <view class="ip-stats">
              <view class="stat-item">
                <text class="stat-icon">❤️</text>
                <text class="stat-value">{{ ip.likes }}</text>
              </view>
              <view class="stat-item">
                <text class="stat-icon">📥</text>
                <text class="stat-value">{{ ip.downloads }}</text>
              </view>
              <view class="stat-item">
                <text class="stat-icon">🔄</text>
                <text class="stat-value">{{ ip.remixes }}</text>
              </view>
            </view>
            
            <view class="ip-tags">
              <text 
                v-for="tag in ip.tags" 
                :key="tag"
                class="ip-tag"
              >{{ tag }}</text>
            </view>
          </view>
          
          <view class="ip-actions">
            <button class="action-btn like-btn" @click.stop="toggleLike(ip)">
              <text class="btn-icon">{{ ip.liked ? '❤️' : '🤍' }}</text>
            </button>
            <button class="action-btn download-btn" @click.stop="downloadIP(ip)">
              <text class="btn-icon">📥</text>
            </button>
            <button class="action-btn remix-btn" @click.stop="remixIP(ip)">
              <text class="btn-icon">🔄</text>
            </button>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="hasMore" class="load-more">
        <button class="load-more-btn" @click="loadMore">
          <text class="btn-text">加载更多</text>
        </button>
      </view>
    </scroll-view>

    <!-- 上传模态框 -->
    <view v-if="showUpload" class="upload-modal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">上传IP作品</text>
          <text class="modal-close" @click="hideUploadModal">×</text>
        </view>
        
        <scroll-view class="modal-scroll" scroll-y="true">
          <view class="upload-form">
            <!-- IP名称 -->
            <view class="form-item">
              <text class="form-label">IP名称</text>
              <input 
                v-model="uploadData.name" 
                class="form-input" 
                placeholder="请输入IP名称"
                placeholder-class="placeholder"
              />
            </view>
            
            <!-- IP描述 -->
            <view class="form-item">
              <text class="form-label">IP描述</text>
              <textarea 
                v-model="uploadData.description" 
                class="form-textarea" 
                placeholder="请详细描述您的IP作品..."
                placeholder-class="placeholder"
                maxlength="500"
              />
              <text class="char-count">{{ uploadData.description.length }}/500</text>
            </view>
            
            <!-- 封面图片 -->
            <view class="form-item">
              <text class="form-label">封面图片</text>
              <view class="cover-upload" @click="chooseCover">
                <image 
                  v-if="uploadData.cover" 
                  :src="uploadData.cover" 
                  class="cover-preview"
                  mode="aspectFill"
                />
                <view v-else class="cover-placeholder">
                  <text class="upload-icon">+</text>
                  <text class="upload-text">选择封面</text>
                </view>
              </view>
            </view>
            
            <!-- 许可协议 -->
            <view class="form-item">
              <text class="form-label">许可协议</text>
              <picker 
                :range="licenses" 
                range-key="name"
                @change="onLicenseChange"
              >
                <view class="picker-value">
                  {{ uploadData.license.name }}
                  <text class="picker-arrow">▼</text>
                </view>
              </picker>
            </view>
            
            <!-- 标签 -->
            <view class="form-item">
              <text class="form-label">标签</text>
              <view class="tags-input">
                <input 
                  v-model="tagInput" 
                  class="tag-input" 
                  placeholder="输入标签后按回车"
                  placeholder-class="placeholder"
                  @confirm="addTag"
                />
                <view class="tags-list">
                  <view 
                    v-for="(tag, index) in uploadData.tags" 
                    :key="index"
                    class="tag-item"
                  >
                    <text class="tag-text">{{ tag }}</text>
                    <text class="tag-remove" @click="removeTag(index)">×</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
        
        <view class="modal-actions">
          <button class="modal-btn cancel" @click="hideUploadModal">取消</button>
          <button class="modal-btn confirm" @click="uploadIP">上传</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchKeyword: '',
      selectedFilter: 'all',
      filters: [
        { value: 'all', name: '全部' },
        { value: 'popular', name: '热门' },
        { value: 'newest', name: '最新' },
        { value: 'free', name: '免费' }
      ],
      ipList: [
        {
          id: 1,
          name: '樱花少女',
          author: '动漫爱好者',
          description: '一个可爱的樱花主题动漫角色设计',
          cover: '/static/ip-cover1.png',
          license: 'cc-by',
          likes: 245,
          downloads: 156,
          remixes: 32,
          tags: ['角色', '可爱', '樱花'],
          liked: false
        },
        {
          id: 2,
          name: '魔法学院',
          author: '幻想家',
          description: '奇幻魔法学院的世界观设定',
          cover: '/static/ip-cover2.png',
          license: 'cc-by-nc',
          likes: 189,
          downloads: 98,
          remixes: 15,
          tags: ['世界观', '奇幻', '学院'],
          liked: true
        }
      ],
      showUpload: false,
      uploadData: {
        name: '',
        description: '',
        cover: '',
        license: { value: 'cc-by', name: 'CC BY 署名' },
        tags: []
      },
      tagInput: '',
      licenses: [
        { value: 'cc-by', name: 'CC BY 署名' },
        { value: 'cc-by-nc', name: 'CC BY-NC 署名-非商业性使用' },
        { value: 'cc-by-sa', name: 'CC BY-SA 署名-相同方式共享' },
        { value: 'all-rights', name: '保留所有权利' }
      ],
      hasMore: true
    }
  },
  computed: {
    filteredIPs() {
      let filtered = this.ipList
      
      // 搜索过滤
      if (this.searchKeyword) {
        filtered = filtered.filter(ip => 
          ip.name.includes(this.searchKeyword) || 
          ip.description.includes(this.searchKeyword) ||
          ip.tags.some(tag => tag.includes(this.searchKeyword))
        )
      }
      
      // 筛选过滤
      switch (this.selectedFilter) {
        case 'popular':
          filtered = filtered.sort((a, b) => b.likes - a.likes)
          break
        case 'newest':
          filtered = filtered.sort((a, b) => b.id - a.id)
          break
        case 'free':
          filtered = filtered.filter(ip => ip.license !== 'all-rights')
          break
      }
      
      return filtered
    }
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    onSearch() {
      // 搜索逻辑已通过计算属性实现
    },
    selectFilter(filter) {
      this.selectedFilter = filter
    },
    viewIPDetail(ip) {
      uni.navigateTo({
        url: `/pages/ip-detail/ip-detail?id=${ip.id}`
      })
    },
    toggleLike(ip) {
      ip.liked = !ip.liked
      ip.likes += ip.liked ? 1 : -1
      
      uni.showToast({
        title: ip.liked ? '已点赞' : '已取消点赞',
        icon: 'success'
      })
    },
    downloadIP(ip) {
      uni.showModal({
        title: '下载确认',
        content: `确定要下载"${ip.name}"吗？`,
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: '下载中...'
            })
            
            setTimeout(() => {
              uni.hideLoading()
              ip.downloads++
              uni.showToast({
                title: '下载成功',
                icon: 'success'
              })
            }, 2000)
          }
        }
      })
    },
    remixIP(ip) {
      uni.showModal({
        title: '二次创作',
        content: `确定要基于"${ip.name}"进行二次创作吗？`,
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/character/character'
            })
          }
        }
      })
    },
    loadMore() {
      // 模拟加载更多数据
      setTimeout(() => {
        this.hasMore = false
        uni.showToast({
          title: '没有更多数据了',
          icon: 'none'
        })
      }, 1000)
    },
    showUploadModal() {
      this.showUpload = true
    },
    hideUploadModal() {
      this.showUpload = false
      this.resetUploadData()
    },
    resetUploadData() {
      this.uploadData = {
        name: '',
        description: '',
        cover: '',
        license: { value: 'cc-by', name: 'CC BY 署名' },
        tags: []
      }
      this.tagInput = ''
    },
    chooseCover() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.uploadData.cover = res.tempFilePaths[0]
        }
      })
    },
    onLicenseChange(e) {
      const index = e.detail.value
      this.uploadData.license = this.licenses[index]
    },
    addTag() {
      if (this.tagInput.trim() && this.uploadData.tags.length < 5) {
        this.uploadData.tags.push(this.tagInput.trim())
        this.tagInput = ''
      }
    },
    removeTag(index) {
      this.uploadData.tags.splice(index, 1)
    },
    uploadIP() {
      if (!this.uploadData.name.trim()) {
        uni.showToast({
          title: '请输入IP名称',
          icon: 'none'
        })
        return
      }
      
      if (!this.uploadData.description.trim()) {
        uni.showToast({
          title: '请输入IP描述',
          icon: 'none'
        })
        return
      }
      
      if (!this.uploadData.cover) {
        uni.showToast({
          title: '请选择封面图片',
          icon: 'none'
        })
        return
      }
      
      uni.showLoading({
        title: '上传中...'
      })
      
      // 模拟上传过程
      setTimeout(() => {
        uni.hideLoading()
        
        const newIP = {
          id: Date.now(),
          name: this.uploadData.name,
          author: '当前用户',
          description: this.uploadData.description,
          cover: this.uploadData.cover,
          license: this.uploadData.license.value,
          likes: 0,
          downloads: 0,
          remixes: 0,
          tags: this.uploadData.tags,
          liked: false
        }
        
        this.ipList.unshift(newIP)
        this.hideUploadModal()
        
        uni.showToast({
          title: '上传成功',
          icon: 'success'
        })
      }, 2000)
    },
    getLicenseText(license) {
      const licenseMap = {
        'cc-by': 'CC BY',
        'cc-by-nc': 'CC BY-NC',
        'cc-by-sa': 'CC BY-SA',
        'all-rights': '版权'
      }
      return licenseMap[license] || 'CC BY'
    }
  }
}
</script>

<style scoped>
.ip-sharing-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #FFE4E